#!/usr/bin/env bash

print_help_info(){
  exec echo "
CI-CLI 2.16.0

Donate WebSite https://zan.khs1994.com

Usage: ./ci COMMAND options

Debug: DEBUG=1 ./ci COMMAND options

Options:
  -d                     后台运行

  --use-external-nginx   使用外部 NGINX = 后边值为配置文件路径 (TLS Only)

  --config               生成 docker-compose.yml 文件

Commands:
  up           [-d]
  down

  up-tls       [-d] [--use-external-nginx=/etc/nginx/conf.d]

  swarm-deploy [TODO]
  swarm-remove [TODO]

  k8s-create [TODO]
  k8s-delete [TODO]

  reset                   重置，恢复原始状态

Read './docs/*.md' for more information about CLI commands.

You can open issue in [ https://github.com/khs1994-docker/ci/issues ] when you meet problems.

You must Update .env file when update this project.
"
}

_cp(){
  if [ ! -f $2 ];then cp $1 $2; fi
}

_init(){
  _cp .env.example .env
  _cp config/gitea/app.kubernetes.example.ini config/gitea/app.kubernetes.ini
  set +e
  docker compose version > /dev/null 2>&1

  if [ $? -ne 0 ];then exec echo "Error: docker compose v2 not install" ; fi
  set -e
}

_reset_(){
  rm -rf config/gogs/app.ini \
      config/registry/config.yml \
      config/nginx/*.conf
}

_reset(){
  _reset_
  rm -rf .env docker-ci.override.yml
}

_sed_common(){
  sed -e "s#{{ DB_TYPE }}#${CI_DB_TYPE:-mysql}#g" \
    config/gogs/app.example.ini \
    > config/gogs/app.ini

  if ! [ -f docker-ci.override.yml ];then
    sed -e "s#{{ DB_TYPE }}#${CI_DB_TYPE:-mysql}#g" \
      git-compose/${CI_GIT_TYPE:-gogs}-compose.yaml \
      > docker-ci.override.yml
  fi

  files="config/gogs/app.ini docker-ci.override.yml"

  for file in $files;
  do
    sed -i -e "s#{{ DB_HOST }}#${CI_EXTERNAL_MYSQL_HOST:-mysql}:${CI_EXTERNAL_MYSQL_PORT:-3306}#g" \
      -e "s#{{ DB_DATABASE }}#${CI_EXTERNAL_MYSQL_DATABASE:-$MYSQL_DATABASE}#g" \
      -e "s#{{ DB_USERNAME }}#${CI_EXTERNAL_MYSQL_USERNAME:-root}#g" \
      -e "s#{{ DB_PASSWORD }}#${CI_EXTERNAL_MYSQL_PASSWORD:-$MYSQL_ROOT_PASSWORD}#g" \
      $file
  done

  sed -i -e "s#{{ MAIL_HOST }}#${CI_MAIL_HOST}#g" \
    -e "s#{{ MAIL_FROM }}#${CI_MAIL_FROM}#g" \
    -e "s#{{ MAIL_USERNAME }}#${CI_MAIL_USERNAME}#g" \
    -e "s#{{ MAIL_PASSWORD }}#${CI_MAIL_PASSWORD}#g" \
    -e "s#{{ SSH_PORT }}#${CI_GOGS_SSH_PORT:-8022}#g" \
    config/gogs/app.ini

  cp config/registry/config.example.yml config/registry/config.yml
}

_up_sed(){
  sed -i -e "s#{{ DRONE_SERVER_HOST }}#${CI_HOST:-192.168.199.100}:${CI_DRONE_PORT:-8000}#g" \
    -e "s#{{ DRONE_GOGS_SERVER }}#http://${CI_HOST:-192.168.199.100}:${CI_GOGS_PORT:-3000}#g" \
    -e "s#{{ DRONE_SERVER_PROTO }}#http#g" \
    docker-ci.override.yml
}

_up(){
    _reset_ ; _init
    _sed_common

    sed -i -e "s#{{ CI_DOMAIN }}#${CI_HOST:-192.168.199.100}#g" \
      -e "s#{{ CI_DOMAIN_FULL }}#${CI_HOST:-192.168.199.100}#g" \
      -e "s#{{ CI_GOGS_PORT }}#${CI_GOGS_PORT:-3000}#g" \
      -e "s#{{ PROTOCOL }}#http#g" \
      -e "s!^CERT_FILE.*!#CERT_FILE!g" \
      -e "s!^KEY_FILE.*!#KEY_FILE!g" \
      -e "s!^TLS_MIN_VERSION.*!#TLS_MIN_VERSION!g" \
      config/gogs/app.ini

    sed -i -e "s#{{ REDIS_HOST }}#${CI_EXTERNAL_REDIS_HOST:-$REDIS_HOST}#g" \
      -e "s#{{ WEBHOOKS_HOST }}#${WEBHOOKS_HOST:-http://192.168.199.100}#g" \
      config/registry/config.yml

  _up_sed

  CI_INCLUDE=${CI_INCLUDE-drone-server drone-docker-runner gogs registry}

  # based posrt don't up nginx

  for soft in $CI_INCLUDE
  do
    if [ $soft = 'nginx' ];then continue; fi
    CI_INCLUDE_TARGET+="$soft "
  done

  docker compose ${COMPOSE_FILE:?err} config > docker-compose.yml

  if [ -n "${CI_COMPOSE_CONFIG_ONLY}" ];then return;fi

  docker compose ${COMPOSE_FILE:?err} up ${CI_COMPOSE_OPT:-} \
    ${CI_INCLUDE_TARGET} drone-server drone-docker-runner
}

_up-tls_sed(){
  sed -i -e "s#{{ DRONE_SERVER_HOST }}#drone.${CI_DOMAIN:-t.khs1994.com}#g" \
    -e "s#{{ DRONE_GOGS_SERVER }}#https://git.${CI_DOMAIN:-t.khs1994.com}#g" \
    -e "s#{{ DRONE_SERVER_PROTO }}#https#g" \
    docker-ci.override.yml
}

_up-tls(){
  _reset_ ; _init
  _sed_common

  sed -i -e "s#{{ CI_DOMAIN }}#${CI_DOMAIN:-t.khs1994.com}#g" \
      -e "s#{{ CI_DOMAIN_FULL }}#git.${CI_DOMAIN:-t.khs1994.com}#g" \
      -e "s#{{ CI_GOGS_PORT }}#${CI_GOGS_PORT:-443}#g" \
      -e "s#{{ PROTOCOL }}#https#g" \
      config/gogs/app.ini

  sed -i -e "s#{{ REDIS_HOST }}#${CI_EXTERNAL_REDIS_HOST:-$REDIS_HOST}#g" \
      -e "s#{{ WEBHOOKS_HOST }}#${WEBHOOKS_HOST:-https://ci.t.khs1994.com/docker/webhooks}#g" \
      config/registry/config.yml

  _up-tls_sed

  _sed_external_nginx(){
    # 使用外部 NGINX
    cd config/nginx

    for file in $( ls *.config )
    do
      sed -e "s#{{ CI_DOMAIN }}#${CI_DOMAIN:-t.khs1994.com}#g" \
          -e "s#{{ REGISTRY_UPSTREAM }}#${CI_HOST:-192.168.199.100}#g" \
          -e "s#{{ DRONE_UPSTREAM }}#${CI_HOST:-192.168.199.100}#g" \
          -e "s#{{ GOGS_UPSTREAM }}#${CI_HOST:-192.168.199.100}#g" \
          $file >> $(echo $file | cut -d '.' -f 1 | cut -d '-' -f 2).conf
    done

    if [ "$LNMP_NGINX_CONF" != '--use-external-nginx' ];then
      if ! [ -d "$LNMP_NGINX_CONF" ];then return ; fi

      cp -a $PWD/*.conf $LNMP_NGINX_CONF

      mkdir -p $LNMP_NGINX_CONF/ssl || echo

      if ! [ -f ssl/$CI_DOMAIN.crt ];then cp -a $PWD/ssl/*  $LNMP_NGINX_CONF/ssl; fi
    fi

    cd - > /dev/null
  }

  _sed_nginx(){
    # 使用内部 NGINX
    cd config/nginx

    for file in `ls *.config`
    do
      sed -e "s#{{ CI_DOMAIN }}#${CI_DOMAIN:-t.khs1994.com}#g" \
          -e "s#{{ REGISTRY_UPSTREAM }}#registry#g" \
          -e "s#{{ DRONE_UPSTREAM }}#drone-server#g" \
          -e "s#{{ GOGS_UPSTREAM }}#gogs#g" \
          $file >> $(echo $file | cut -d '.' -f 1 | cut -d '-' -f 2).conf
    done

    cd - > /dev/null
  }

  test "$ENABLE_NGINX" = 'FALSE' && _sed_external_nginx || _sed_nginx

  docker compose ${COMPOSE_FILE:?err} config > docker-compose.yml

  if [ -n "${CI_COMPOSE_CONFIG_ONLY}" ];then return;fi

  docker compose ${COMPOSE_FILE:?err} up ${CI_COMPOSE_OPT:-} \
    ${CI_INCLUDE-gogs registry} drone-server drone-docker-runner
}

_down(){
  docker compose down --remove-orphans
}

_logs(){
  if ! [ -f logs/nginx/access.log ];then
    mkdir -p logs/nginx
    touch logs/nginx/access.log
    touch logs/nginx/error.log
  fi
}

set -e

_logs

if [ "$DEBUG" = 'true' ];then set -x; fi

OS=`uname -s`

# test $OS = 'Darwin' && export PATH=/usr/local/opt/gnu-sed/libexec/gnubin:$PATH

if [ $OS = 'Darwin' -a ! -f /usr/local/opt/gnu-sed/libexec/gnubin/sed ];then
  print_info "please install gnu-sed by EXEC:

\$ brew install gnu-sed"

  exit 1
fi

if [ $OS = 'Darwin' ];then
  alias sed=gsed
fi

_init

. $PWD/.env
. $PWD/secrets/mysql.env

if [ -f $HOME/.bash_profile ];then . ~/.bash_profile; fi

test "$#" = 0 && print_help_info || true

command=$1

shift

if [ -z "$CI_HOST" -a "$command" = 'up' ];then exec echo "Error: CI_HOST not set";fi

if [ -z "$CI_DOMAIN" -a "$command" = 'up-tls' ];then
  exec echo "Error:  CI_DOMAIN not set"
fi

COMPOSE_FILE='-f docker-ci.yml -f docker-ci.override.yml'
CI_COMPOSE_CONFIG_ONLY=
CI_COMPOSE_OPT=

for arg in "$@"
do
  test $arg = '-d' && CI_COMPOSE_OPT='-d' || true
  test $arg = '--config' && CI_COMPOSE_CONFIG_ONLY=1 || true
  [[ $arg =~ --use-external-nginx=* ]] && \
    ENABLE_NGINX=FALSE && LNMP_NGINX_CONF=$( echo $arg | cut -d '=' -f 2 ) || true
done

_$command "$@"
